package client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MultiThreadClient implements Runnable {
	// Declaration section
	// clientClient: the client socket
	// os: the output stream
	// is: the input stream

	static Socket clientSocket = null;
	static PrintStream os = null;
	static DataInputStream is = null;
	static BufferedReader inputLine = null;
	static boolean closed = false;
	static String command = null;
	private static String record = null;
	public static String host = "localhost";

	public static int port_number = 1234;
	
	public static void main(String[] args) {

		// The default port


		if (args.length < 2) {
			System.out.println("Witaj w systemie SR.");
			printMenu();
		} else {
			host = args[0];
			port_number = Integer.valueOf(args[1]).intValue();
		}
		// Initialization section:
		// Try to open a socket on a given host and port
		// Try to open input and output streams
		try {
			clientSocket = new Socket(host, port_number);
			inputLine = new BufferedReader(new InputStreamReader(System.in));
			os = new PrintStream(clientSocket.getOutputStream());
			is = new DataInputStream(clientSocket.getInputStream());
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host " + host);
		} catch (IOException e) {
			System.err
					.println("Couldn't get I/O for the connection to the host "
							+ host);
		}

		// If everything has been initialized then we want to write some data
		// to the socket we have opened a connection to on port port_number

		if (clientSocket != null && os != null && is != null) {
			try {
				// Create a thread to read from the server
				new Thread(new MultiThreadClient()).start();
				String line;
				while (!closed) {
					command = line = inputLine.readLine();
					if (line == null)
						break;
					switch (line) {
					case "a":
						System.out.println("Podaj wartosc rekordu.");
						record = inputLine.readLine();
						System.out.println("Podaj id rekordu.");
						String recId = inputLine.readLine();
						os.println("KADD,"+recId+","+record);
						break;
					case "d":
						System.out.println("Podaj id rekordu do usuniecia.");
						int id = Integer.valueOf(inputLine.readLine());
						os.println("KCHECK," + id);
						break;
					case "m":
						System.out.println("Podaj id rekordu do modyfikacji.");
						id = Integer.valueOf(inputLine.readLine());
						System.out.println("Podaj wartosc rekordu.");
						record = inputLine.readLine();
						os.println("KCHECK," + id);
						break;
					case "s":
						os.println("KSHOW");
						break;
					case "t":
						os.println("KTEST");
						break;
					case "q":
						os.println("KQUIT");
						break;
					default:
						System.out.println("Nieznane polecenie.");
					}
				}

				cleanUp();
			}catch (IOException e) {
				System.err.println("IOException:  " + e);
			}
		}
	}

	private static void clear() {
		record = null;
		command = null;
	}

	private static void cleanUp() throws IOException {
		os.close();
		is.close();
		clientSocket.close();
	}

	@SuppressWarnings("deprecation")
	public void run() {
		String responseLine;

		// Keep on reading from the socket till we receive the "Bye" from the
		// server,
		// once we received that then we want to break.
		try {
			while ((responseLine = is.readLine()) != null) {
				String[] elements = responseLine.split(",");
				// System.out.println(responseLine);
				if (responseLine.equals("QCONFIRMED")) {
					System.out.println("Polecenie wykonano.");
					printMenu();
					clear();
				} else if (elements[0].equals("QGRANTED")) {
					Integer id = Integer.valueOf(elements[1]);
					os.println("KCOMMIT," + id + "," + record);
					clear();
				} else if (elements[0].equals("QDENYED")) {
					System.out.println("Rekord jest zajety.");
					clear();
					printMenu();
				} else if (responseLine.equals("QQUIT")
						|| responseLine.equals("")) {
					os.println("Rozlaczony.");
					break;
				} else if (responseLine.contains("{")) {
					System.out.println(responseLine);
					clear();
					printMenu();
				}
			}
			closed = true;
			
		} catch (SocketException e) {
			System.err.println("Odlaczono serwer");
			closed=true;
			try {
				cleanUp();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			System.err.println("IOException:  " + e);
		}
	}

	private static void printMenu() {
		System.out.println("a - dodaj nowy rekord do bazy danych.");
		System.out.println("d - usun rekord z bazy danych.");
		System.out.println("m - modyfukuj rekord z bazy danych.");
		System.out.println("s - wyswietl rekordy z bazy danych.");
		System.out.println("t - test");
		System.out.println("q - wyjscie.");
	}

}
